package com.zhkj.txg.module.find.adapter

import android.text.TextUtils
import android.widget.ImageView
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.zhkj.txg.R
import com.zhkj.txg.module.find.entity.FindPictureEntity
import com.zhkj.txg.utils.ImageUtils

class FindPictureAdapter(private val maxCount: Int) :
    BaseMultiItemQuickAdapter<FindPictureEntity, BaseViewHolder>() {

    init {
        addItemType(FindPictureEntity.TYPE_ADD, R.layout.item_find_pic_add)
        addItemType(FindPictureEntity.TYPE_PIC, R.layout.item_find_pic_pic)
        addChildClickViewIds(R.id.ivPicDelete)
    }

    override fun convert(helper: BaseViewHolder, item: FindPictureEntity) {
        if (item.itemType == FindPictureEntity.TYPE_PIC) {
            val imageView = helper.getView<ImageView>(R.id.ivFindPicture)
            ImageUtils.loadRoundCornerImage(context, imageView, item.pictureFilePath ?: "")
        }
    }

    /**
     * 获取实际选择的照片数量
     */
    fun getRealPictureCount(): Int {
        var realCount = 0
        for (entity in data) {
            if (!TextUtils.isEmpty(entity.pictureFilePath)) realCount += 1
        }
        return realCount
    }

    /**
     * 删除图片
     */
    fun deletePicture(index: Int) {
        data.removeAt(index)
        if (data.size == maxCount - 1 && data.last().itemType != FindPictureEntity.TYPE_ADD) {
            data.add(FindPictureEntity().apply {
                itemType = FindPictureEntity.TYPE_ADD
            })
        }
        notifyDataSetChanged()
    }

    /**
     * 添加图片数据
     */
    fun addPicture(list: List<FindPictureEntity>) {
        if (data.isEmpty()) {
            data.addAll(list)
            if (data.size < maxCount) data.add(
                FindPictureEntity().apply {
                    itemType = FindPictureEntity.TYPE_ADD
                })
        } else {
            if (data.last().itemType == FindPictureEntity.TYPE_ADD) {
                data.removeAt(data.lastIndex)
            }
            data.addAll(list)
            if (data.size < maxCount) data.add(
                FindPictureEntity().apply {
                    itemType = FindPictureEntity.TYPE_ADD
                })
        }
        notifyDataSetChanged()
    }
}